# -*- coding: utf-8 -*-
class DepartmentController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter, :except => [:getAllDepartmentsForTree, :departmentLock]

  #部门管理主页面。
  def departmentList

  end

  #为树状结构准备的所有部门查询
  def getAllDepartmentsForTree
    begin
      #nodeId =  params["node_id"]
      nodeId = params["node"]
      #如果nodeId=xnode-47或nil或其它非XX_YY组成的值，则说明他是根。
      #只要带有xnode-后面加数字的，都要清0
      if nodeId == nil || (nodeId.include? "xnode-") || nodeId == "0" || nodeId == 0
        is_root = true
        nodeId = 0
      end

      #提取真正的ID
      logger.info "Realy nodeId....................................................."
      oriNodeId = "" #让它变为空字符串，这时说明，用点刷新的节点直接挂在根上。
      if nodeId !=0
        if (nodeId.include? "_")
          oriNodeId = nodeId + "_"
          treeNodeIdArray = nodeId.split("_")
          nodeId = treeNodeIdArray[treeNodeIdArray.size-1]
        else
          #这儿也是一个要判断根的地方
          is_root = true
        end
      end
      treeData="["

      if nodeId == nil || nodeId == 0

        role = Role.find(session[:role_id])
        if role.cross_company == "否"
          departments = Department.where("parent_id = 0 AND company_id = #{session[:company_id]}").order("sub_type,name")
        else
          if params["company_id"].nil?
            departments = Department.where("parent_id = 0").order("sub_type,name")
          else
            departments = Department.where("parent_id = 0 AND company_id = ?", params["company_id"]).order("sub_type,name")
          end
        end

        departments.each do |department|
          treeData.concat("{id:#{department.id},company_name:\"#{department.company.name}\",name:\"#{department.name}\",number:'#{department.number}',sub_type:'#{department.sub_type}',is_locked:#{department.is_locked},description:'#{department.description}',")
          if department.children.length > 0
            treeData.concat("leaf:false")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:false},")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:false,spec:'#{product.spec}',unit_price:'#{product.unit_price}',number:unit_price:'#{product.number}'},")
          else
            treeData.concat("leaf:true")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:true},")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:true,spec:'#{product.spec}',unit_price:'#{product.unit_price}'},")
          end
          treeData.concat("},")
        end
      else
        #以下情况，都是触发了“分支”引发expand后要操作的代码。
        department = Department.find(nodeId)
        #product = Product.find(:include=>["products_components"],:conditions=>["id = ?",nodeId])
        departments = department.children
        departments.each do |department|
          #加“_”的原因是在树中不能有重复的ID，所以要用爷子节点的ID组合来实现。
          #如果它的父节点是根。
          if is_root
            oriNodeId = nodeId.to_s + "_"
          end
          treeData.concat("{id:#{department.id},company_name:\"#{department.company.name}\",name:'#{department.name}',number:'#{department.number}',sub_type:'#{department.sub_type}',is_locked:#{department.is_locked},description:'#{department.description}',")
          #if productComponent.component.components.length > 0,另换一种判断方法
          if department.children.length > 0
            treeData.concat("leaf:false")
          else
            treeData.concat("leaf:true")
          end
          treeData.concat("},")
        end
      end

      treeData = treeData[0, treeData.size-1]
      treeData.concat("]")
      #treeData = "[{name:'11111',leaf:true},{name:'22222',leaf:true}]"
      logger.info treeData
      render :text => treeData, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  def getAllDepartments
    forCBB = params[:for_cbb]
    role = Role.find(session[:role_id])
    if role.cross_company == "否"
      if forCBB == 'true'
        departments = Department.select("id,name,number").where("is_locked = ? and company_id = ?", 0, session[:company_id]).order('sub_type,name')
      else
        departments = Department.where("company_id = ?", session[:company_id]).order('sub_type,name')
      end
    else
      if forCBB == 'true'
        departments = Department.select("id,name,number").where(["is_locked = ?", 0]).order('sub_type,name')
      else
        departments = Department.order('sub_type,name')
      end
    end

    jsonStr="{totalProperty:"+departments.length.to_s+",root:"+departments.to_json()+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #显示添加新部门页面
  def newDepartment
  end

  #显示编辑部门页面
  def editDepartment

  end

  def create
    begin
      department = Department.new()
      department.company_id = params[:company_id]
      department.parent_id = params[:parent_id]
      department.name = params[:name]
      department.number = params[:number]
      department.sub_type = params[:sub_type]
      department.description = params[:description]
      department.save!
      info = "成功"
    rescue Exception => e
      info = e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #编辑前的数据准备
  def edit
    department = Department.find(params[:id])
    rootStr = department.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    render :text => jsonStr, :layout => false
  end

  #把编辑后的数据，更新到数据库中
  def update
    begin
      department = Department.find(params[:id])
      department.company_id = params[:company_id]
      department.name = params[:name]
      department.number = params[:number]
      department.sub_type = params[:sub_type]
      department.description = params[:description]
      department.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  def destroy

    id = params[:id]
    department = Department.find(id)
    department.destroy()
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #锁定或解锁销售类型
  def departmentLock
    department = Department.find(params[:id])
    if department.is_locked == 1
      department.is_locked = 0
    else
      department.is_locked = 1
    end
    department.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

end
